<?php

namespace Lib\Loaders;

use Base\LoaderInterface;
use EasySwoole\Component\Di;
use EasySwoole\Utility\File;

class ConfigLoader implements LoaderInterface
{
    public static function handle()
    {
        $di = Di::getInstance();

        // 先放env后放config
        $envConfig = self::getEnvConfig();
        $di->set("env", $envConfig);

        $configs = self::getAllConfig();
        $di->set("config", $configs);
    }

    private static function getAllConfig()
    {
        $configRes = [];
        $configFiles = File::scanDirectory(EASYSWOOLE_ROOT . '/Config');
        if (!empty($configFiles['files'])) {
            foreach ($configFiles['files'] as $file) {
                $_ = explode('/', $file);
                $configRootName = str_replace('.php', '', $_[count($_) - 1]);
                if (file_exists($file)) {
                    $config = include_once($file);
                } else {
                    $config = [];
                }
                $configRes[$configRootName] = $config;
            }
        }
        return $configRes;
    }

    private static function getEnvConfig()
    {
        $envFilePath = EASYSWOOLE_ROOT . '/.env';
        if (!file_exists($envFilePath)) {
            die(".env 不存在" . PHP_EOL);
        }
        $envFileContent = file_get_contents($envFilePath);
        $configRes = [];
        foreach (explode("\n", $envFileContent) as $line) {
            $_ = explode("=", $line);
            if (count($_) == 2 && $_[0] !== '') {
                $configRes[trim($_[0])] = trim($_[1]);
            }
        }
        return $configRes;
    }
}
